import 'dart:async';
import 'dart:convert';

import 'package:star_author/config/app.dart';
import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/route/route_util.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/event.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/stream/dialog/delete_word_dialog.dart';
import 'package:star_author/widgets/dialog/get_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import '../../event_bus/global_event_bus.dart';
import '../../event_bus/rong_im_message_come_event.dart';
import '../../event_bus/rong_im_message_event.dart';
import '../../event_bus/socket_subscription_event.dart';
import '../../utils/common_util/toast/custom_toast.dart';
import '../../utils/toast_util.dart';
import '../../widgets/dialog/bottom_sheet.dart';
import 'dialog/user_info.dart';
import 'model/live_good_list_entity.dart';
import 'stream_rtc.dart';
import 'stream_rtc_bottom.dart';
import 'stream_rtc_top.dart';

enum LiveFrom { User, Anchor }

class barrageList extends StatefulWidget {
  LiveFrom liveFrom;
  LiveForm liveForm;

  barrageList({this.liveFrom: LiveFrom.User, this.liveForm: LiveForm.List});

  @override
  State<barrageList> createState() => _barrageListState();
}

class _barrageListState extends State<barrageList> {
  AutoScrollController controller = AutoScrollController();

  List barrages = [];

  String id = "";

  String tips = "";

  Map firstTips = {"firstTips": ""};

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) async {
      initStream();
    });
  }

  late Timer? timer = null;

  int timer_count = 3;

  bool isConnect = true;

  List<String> msgList = [];

  init() async {
    barrages.clear();
    stream = GlobalEventBus().bus.on<SocketSubscriptionEvent>().listen((event) {
      SocketSubscriptionEvent arg = event;
      var message = arg.message['message'];
      if (message != null) {
        String action = message['action'] ?? "";
        if (action == "join_studio") {
        } else if (action == "close_studio") {
          if (widget.liveFrom == LiveFrom.User) {
            //主播下播
            // StreamConf.status = StreamStatus.NoLiveNotice;
            StreamConf.uid = -1;
            //踢出当前直播间
            CustomToast.show("主播已下线,将在三秒后强制退出直播间或自行退出");
            timer = Timer.periodic(Duration(seconds: 1), (_timer) {
              if (timer_count == 0) {
                _timer.cancel();
                timer!.cancel();
                Get.back();
              }
              timer_count--;
            });
          }
          // CustomToast.show("当前主播已下播");
        } else if (['ban_user', 'unban_user'].contains(action)) {
          GlobalEventBus.instance.bus.fire(MuteMessageEvent(message));
        }
        if (StreamConf.live_actions.contains(action)) {
          int view_users_count = message['view_users_count'] ?? 0;
          valueNotifier.setCount(view_users_count);
        }
      }
    });
    id = UserUtil.getUserId(Get.context!).toString();
    if (id == '0') {
      ToastUtil.show('请重新登录');
      RouteUtil.onVerifyLogin();
      return;
    }
    if (widget.liveFrom == LiveFrom.User) {
      if (StreamConf.channelModel!.interaction) {
        tips = "连麦鉴宝请点击底部连麦图标申请连麦。";
      }
      firstTips['firstTips'] =
          "欢迎来到直播间~$tips\n\n请各位文明发言，任何传播违法、违规、低俗、暴力等不良信息的账号将会被禁言并可能封停账号。";
      barrages.add(firstTips);
      msgList.add("-1");
    }
    //小窗口进来的
    if (!StreamConf.isJoinRongCould) {
      initMessages();
    }

    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      if (controller.hasClients) {
        controller.animateTo(controller.position.maxScrollExtent,
            duration: Duration(milliseconds: 666),
            curve: Curves.easeInOutCubic);
      }
    });

    controller.addListener(() {
      if (controller.position.maxScrollExtent == controller.offset) {
        //当前已经在底部了 表示没有滑动
        needJump = true;
        newCount = 0;
      } else {
        needJump = false;
      }
    });
  }

  initMessages() async {
    List? msgs = await RongUtil.getHistoryMessages();
    if (msgs != null) {
      msgs = msgs.reversed.toList();
      for (int i = 0; i < msgs.length; i++) {
        Message msg = msgs[i] as Message;
        MessageContent? content = msg.content;
        if (content != null) {
          if (content is TextMessage) {
            if (content.content != null) {
              Map map = json.decode(content.extra ?? "");
              if (msg.messageUId!.isNotEmpty) {
                switch (map['operation'] ?? "") {
                  case OperationKey.send_words:
                    int indexWhere = msgList
                        .indexWhere((element) => element == msg.messageUId);
                    bool has_et =
                        (content.mentionedInfo?.userIdList?.length ?? 0) >
                            0; //是否有艾特消息
                    if (has_et) {
                      String et_id =
                          content.mentionedInfo?.userIdList?[0] ?? "0";
                      if (et_id == id) {
                        //判断本地是否读取过当前消息 如果读取过当前消息就不添加
                        int index_where = local_et_messages_list
                            .indexWhere((element) => msg.messageUId == element);
                        if (index_where == -1) {
                          et_list.add(msg.messageUId);
                        }
                      }
                    }
                    if (indexWhere == -1) {
                      update(() {
                        Map map2 = Map();
                        map2.addAll(map['data']);
                        map2.addAll({
                          "be_user_info": map['be_user_info'],
                        });
                        barrages.add(map2);
                        msgList.add(msg.messageUId!);
                      });
                    } else {
                      Map map2 = Map();
                      map2.addAll(map['data']);
                      map2.addAll({
                        "be_user_info": map['be_user_info'],
                      });
                      barrages[indexWhere] = (map2);
                      msgList[indexWhere] = (msg.messageUId!);
                    }
                    break;
                }
              }
            }
          }
        }
      }
    }
  }

  StreamSubscription<RongIMMessageEvent>? _streamSubscriptionstream;
  StreamSubscription<RongIMMessageComeEvent>? _streamSubscriptionstream2;
  //艾特消息
  List et_list = [];

  int et_index = -1;

  //本地消息列表
  List<dynamic> local_et_messages_list = [];

  //上一次获取到消息的时间
  String local_et_messages_time = "";

  getEtSettings() {
    Map? local_et_messages = SpUtil.getObject(App.et_stream_key);
    if (local_et_messages?.isNotEmpty ?? false) {
      local_et_messages_list = local_et_messages?['list'] ?? [];
      local_et_messages_time =
          local_et_messages?['local_et_messages_time'] ?? "";
    }
  }

  setEtSettings(String uid) {
    local_et_messages_list.add(uid);
    SpUtil.putObject(App.et_stream_key, {
      "list": local_et_messages_list,
      "local_et_messages_time": DateUtil.getNowDateStr(),
    });
  }

  clearEtList() {
    SpUtil.putObject(App.et_stream_key, {
      "list": [],
      "local_et_messages_time": DateUtil.getNowDateStr(),
    });
  }

  initStream() {
    getEtSettings();
    RongIMClient.onRecallMessageReceived = (Message? message) async {
      if (message?.targetId == StreamConf.channelKey) {
        // 消息接受者处于当前会话时，收到发送者撤回通知，更新消息列表移除或标记被撤回消息
        // 撤回消息不属于当前会话，无需处理，加载消息消息是，原消息会被替换为撤回通知消息
        int indexWhere =
            msgList.indexWhere((element) => element == message?.messageUId);
        if (indexWhere != -1) {
          update(() {
            barrages.removeAt(indexWhere);
            msgList.removeAt(indexWhere);
          });
        }
      }
    };

    _streamSubscriptionstream =
        GlobalEventBus().bus.on<RongIMMessageEvent>().listen((event) async {
      if (event.message.content is TextMessage) {
        TextMessage msg = event.message.content as TextMessage;
        Map map = json.decode(msg.extra!);
        String _msg_content = msg.content ?? "";
        map['data']['words'] = _msg_content;
        String uid = event.message.messageUId!;
        bool has_et =
            (msg.mentionedInfo?.userIdList?.length ?? 0) > 0; //是否有艾特消息
        if (has_et) {
          String et_id = msg.mentionedInfo?.userIdList?[0] ?? "0";
          if (et_id == id) {
            //判断本地是否读取过当前消息 如果读取过当前消息就不添加
            int index_where =
                local_et_messages_list.indexWhere((element) => uid == element);
            if (index_where == -1) {
              et_list.add(uid);
            }
          }
        }
        if (map.isNotEmpty) {
          int indexWhere = msgList
              .indexWhere((element) => element == event.message.messageUId);
          if (indexWhere == -1) {
            if ([
              OperationKey.send_words,
              OperationKey.join_explanation,
              OperationKey.connecting_mic_barrage,
              OperationKey.close_connecting_mic_barrage
            ].contains(map['operation'])) {
              update(() {
                Map map2 = Map();
                map2.addAll(map['data']);
                map2.addAll({
                  "be_user_info": map['be_user_info'],
                });
                barrages.add(map2);
                msgList.add(uid);
              });
              WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
                if (barrages.length > 6) {
                  if (needJump) {
                    controller.animateTo(controller.position.maxScrollExtent,
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeIn);
                  } else {
                    update(() {
                      newCount++;
                    });
                  }
                } else {
                  controller.animateTo(controller.position.maxScrollExtent,
                      duration: Duration(milliseconds: 300),
                      curve: Curves.easeIn);
                }
              });
            } else if (map['operation'] == OperationKey.join_chat_room) {
              joinChatRoom(map);
            } else if (map['operation'] == OperationKey.stop_live) {}
          } else {
            barrages[indexWhere] = (map['data']);
            msgList[indexWhere] = (uid);
          }
        }
      }
    });
    _streamSubscriptionstream2 =
        GlobalEventBus().bus.on<RongIMMessageComeEvent>().listen((event) async {
      if (event.message.content is TextMessage) {
        TextMessage msg = event.message.content as TextMessage;
        Map map = json.decode(msg.extra!);
        if (map.isNotEmpty) {
          if ([OperationKey.join_chat_room].contains(map['operation'])) {
            //加入房间
            joinChatRoom(map);
          }
        }
      }
    });
    init();
  }

  joinChatRoom(map) {
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      come = map['data'];
      showCome = true;
      count = 3;
      update(() {});
      timer = Timer.periodic(Duration(seconds: 1), (_timer) {
        if (count <= 0) {
          _timer.cancel();
          timer?.cancel();
          update(() {
            showCome = false;
          });
        }
        count--;
      });
    });
  }

  var come = {};

  int count = 3;

  bool showCome = false;

  double fontSize = 12.sp;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _streamSubscriptionstream?.cancel();
    _streamSubscriptionstream2?.cancel();
    if (widget.liveFrom == LiveFrom.User) {
      if (StreamConf.uid != -1) {
        StreamConf.barrages = barrages;
      } else {
        StreamConf.barrages = [];
        StreamConf.viewUserCount = 0;
      }
    }
    stream?.cancel();
    barrages = [];
    if (timer != null) {
      timer?.cancel();
    }
  }

  late StreamSubscription<SocketSubscriptionEvent>? stream = null;

  bool needJump = true; //是否自动跳转

  int newCount = 0;

  //**来了组件
  Widget buildComeWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Container(
            margin: EdgeInsets.symmetric(
              horizontal: 12.w,
            ),
            constraints:
                BoxConstraints(minWidth: 1, maxWidth: Get.width * 0.66),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.0.w),
                gradient: LinearGradient(colors: [
                  Color(0x4DFF8F4F).withAlpha(70),
                  Color(0x4DFF8F4F).withAlpha(30),
                ])),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                //左侧是图片
                if (come.isNotEmpty)
                  come['is_bidder']
                      ? Container(
                          margin: EdgeInsets.only(right: 10.0.w),
                          child: Image.asset(
                            'images/lt_user/level/level_${come['user_level']}.png',
                            width: 22.w,
                            height: 12.w,
                            fit: BoxFit.cover,
                          ),
                        )
                      : Container(),
                //右侧是文字自适应
                Container(
                  child: Container(
                    constraints:
                        BoxConstraints(minWidth: 1, maxWidth: Get.width * 0.5),
                    child: Text(
                      '${come['user_nickname'] ?? ""} 来了',
                      style: TextStyle(
                          fontSize: fontSize,
                          color: Colors.white,
                          fontWeight: FontWeight.w500),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                )
              ],
            ),
            padding:
                EdgeInsets.only(right: 14.w, left: 8.w, top: 5.w, bottom: 5.w),
          )
        ],
      ),
    );
  }

  //加入讲解队列
  Widget buildSerialWidget(LiveGoodListData liveData) {
    return GestureDetector(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            child: Text(
              "${liveData.goods?.serial} 加入讲解列队",
              style: TextStyle(
                fontSize: 12.sp,
                color: Color(0xFFE9D095),
              ),
            ),
            margin: EdgeInsets.only(left: 12.w, top: 5.w),
            constraints: BoxConstraints(
              minWidth: 1,
              maxWidth: Get.width * (268.w / 375.w),
            ),
            padding:
                EdgeInsets.only(right: 12.w, left: 8.w, top: 5.w, bottom: 5.w),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15.0.w),
                color: Color(0x4D000000)),
          )
        ],
      ),
      onTap: () {},
    );
  }

  Widget buildConnectTypeWidget(int index) {
    String connect_type = barrages[index]['connect_type'];
    String suffixStr = "";
    if (connect_type == "disconnect") {
      //结束连麦
      suffixStr = "连麦鉴宝结束";
    } else if (connect_type == "connect") {
      //结束连麦
      suffixStr = "开始连麦鉴宝";
    }
    String nick_name = barrages[index]['nickname'] ?? "";
    if (nick_name.length >= 10) {
      nick_name = nick_name.substring(0, 9) + "...";
    }
    return GestureDetector(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            child: Text(
              "${nick_name} $suffixStr",
              style: TextStyle(
                fontSize: 12.sp,
                color: Color(0xFFE9D095),
              ),
            ),
            margin: EdgeInsets.only(left: 12.w, top: 5.w),
            constraints: BoxConstraints(
              minWidth: 1,
              maxWidth: Get.width * (268.w / 375.w),
            ),
            padding:
                EdgeInsets.only(right: 12.w, left: 8.w, top: 5.w, bottom: 5.w),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15.0.w),
                color: Color(0x4D000000)),
          )
        ],
      ),
      onTap: () {},
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: MediaQuery.removePadding(
        context: context,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Positioned(
              child: Offstage(
                child: buildComeWidget(),
                offstage: !showCome || come.isEmpty,
              ),
              top: -30.w,
            ),
            GestureDetector(
              child: Container(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    buildBarrageListView(),
                    Visibility(
                      child: Container(
                        margin: EdgeInsets.only(
                          top: 10.w,
                        ),
                        child: Row(
                          children: [
                            if (et_list.length > 0)
                              InkWell(
                                child: Container(
                                  margin: EdgeInsets.only(
                                    left: 12.w,
                                  ),
                                  height: 20.w,
                                  alignment: Alignment.center,
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 10.w,
                                  ),
                                  child: Text(
                                    "${et_list.length}条消息@我",
                                    style: TextStyle(
                                        fontSize: 12.sp,
                                        fontWeight: FontWeight.w500,
                                        color: rgba(224, 32, 32, 1)),
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white.withOpacity(0.6),
                                    borderRadius: BorderRadius.circular(12.w),
                                  ),
                                ),
                                onTap: () async {
                                  if (et_list.length <= 0) return;
                                  int index_where = msgList.indexWhere(
                                      (element) => element == et_list[0]);
                                  if (index_where != -1) {
                                    controller.scrollToIndex(
                                      index_where,
                                      duration: Duration(milliseconds: 300),
                                    );
                                    et_index = index_where;
                                    setEtSettings(et_list[0]);
                                    et_list.removeAt(0);
                                  } else {
                                    clearEtList();
                                    et_index = -1;
                                    controller.animateTo(
                                        controller.position.maxScrollExtent,
                                        duration: Duration(milliseconds: 300),
                                        curve: Curves.easeIn);
                                  }
                                  update(() {});
                                },
                              ),
                            Visibility(
                              child: InkWell(
                                child: Container(
                                  height: 20.w,
                                  alignment: Alignment.center,
                                  padding: EdgeInsets.symmetric(
                                    horizontal: 10.w,
                                  ),
                                  margin: EdgeInsets.only(
                                    left: 12.w,
                                  ),
                                  child: Text(
                                    "$newCount条新消息",
                                    style: TextStyle(
                                        fontSize: 12.sp,
                                        fontWeight: FontWeight.w500,
                                        color: UIConstant.color33),
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white.withOpacity(0.6),
                                    borderRadius: BorderRadius.circular(12.w),
                                  ),
                                ),
                                onTap: () {
                                  WidgetsBinding.instance!
                                      .addPostFrameCallback((timeStamp) {
                                    update(() {
                                      needJump = false;
                                      newCount = 0;
                                    });
                                    controller.animateTo(
                                        controller.position.maxScrollExtent,
                                        duration: Duration(milliseconds: 300),
                                        curve: Curves.easeIn);
                                  });
                                },
                              ),
                              visible: newCount > 0,
                            )
                          ],
                        ),
                      ),
                      visible: newCount > 0 || et_list.length > 0,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        removeBottom: true,
        removeLeft: true,
        removeRight: true,
        removeTop: true,
      ),
      constraints: BoxConstraints(
          minHeight: StreamConf.barrageMinHeight,
          maxHeight: StreamConf.barrageMaxHeight +
              (newCount > 0 || et_list.length > 0 ? 25.w : 0),
          minWidth: 100,
          maxWidth: Get.width),
    );
  }

  //当没有弹幕的时候不需要全部填充
  buildBarrageListView() {
    Widget view = ListView.builder(
        shrinkWrap: true,
        controller: controller,
        addAutomaticKeepAlives: false,
        itemCount: barrages.length,
        itemBuilder: (context, index) {
          //加入讲解队列
          if ((barrages[index]['backflows'] ?? {}).isNotEmpty) {
            LiveGoodListData liveData =
                LiveGoodListData.fromJson(barrages[index]['backflows'] ?? {});
            return buildSerialWidget(liveData);
          }
          //连麦管理
          if ((barrages[index]['connect_type'] ?? "").isNotEmpty) {
            return buildConnectTypeWidget(index);
          }
          return AutoScrollTag(
            key: ValueKey(index),
            controller: controller,
            index: index,
            child: GestureDetector(
              child: Row(
                children: [
                  Container(
                    margin: EdgeInsets.only(left: 12.w, top: 5.w),
                    constraints: BoxConstraints(
                      minWidth: 1,
                      maxWidth: Get.width * (250.w / 375.w),
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(15.0.w),
                      color: Color(0x4D000000),
                      border: et_index == index
                          ? Border.all(
                              color: rgba(243, 213, 142, 1),
                              width: et_index == index ? 1 : 0,
                            )
                          : null,
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        //右侧是文字自适应
                        Flexible(
                          child: Container(
                              constraints: BoxConstraints(
                                minWidth: 1,
                                maxWidth: Get.width * (230.w / 375.w),
                              ),
                              child: Builder(
                                builder: (context) {
                                  if (barrages[index]['firstTips'] != null) {
                                    return Text(
                                      '${barrages[index]['firstTips']}',
                                      style: TextStyle(
                                        fontSize: fontSize,
                                        fontWeight: FontWeight.w500,
                                        color: Colors.white,
                                      ),
                                    );
                                  } else {
                                    return buildContentWidget(index);
                                  }
                                },
                              )),
                        ),
                      ],
                    ),
                    padding: EdgeInsets.only(
                        right: 12.w, left: 8.w, top: 5.w, bottom: 5.w),
                  )
                ],
              ),
              onTap: () async {
                if (widget.liveFrom == LiveFrom.Anchor) {
                  if (barrages[index]['firstTips'] == null) {
                    Message? msg =
                        await RongIMClient.getMessageByUId(msgList[index]);
                    showMyBottomSheet(UserInfoDialog(
                      map: barrages[index],
                      banId: barrages[index]['id'].toString(),
                    ));
                  }
                } else if (widget.liveFrom == LiveFrom.User) {
                  //直播间提示 不能举报
                  if (barrages[index]['firstTips'] == null) {
                    if (barrages[index]['id'].toString() == id) {
                      CustomToast.show("不能举报自己哦");
                      return;
                    }
                    showGetDialog(ReportWordDialog(
                      delete: () async {
                        Message? msg =
                            await RongIMClient.getMessageByUId(msgList[index]);
                        Map<String, dynamic>? map = {
                          "owner_id": barrages[index]['id'],
                          "words": barrages[index]['words'],
                          "uid": msg?.messageUId ?? "",
                        };
                        report(map);
                      },
                      deleteWord: barrages[index]['words'] ?? "",
                      uid: msgList[index],
                    ));
                  }
                }
              },
              onLongPress: () {
                if (widget.liveFrom == LiveFrom.Anchor) {
                  showGetDialog(DeleteWordDialog(
                    delete: () async {
                      Message? msg =
                          await RongIMClient.getMessageByUId(msgList[index]);
                      RongUtil.recallMessage(msg!.messageId).then((value) {
                        if (value) {
                          barrages.removeAt(index);
                          msgList.removeAt(index);
                          update(() {});
                        }
                      });
                    },
                    deleteWord: barrages[index]['words'] ?? "",
                    uid: msgList[index],
                  ));
                } else {
                  if (barrages[index]['firstTips'] != null) {
                    CustomToast.show('当前消息不支持回复!');
                    return;
                  }
                  if (barrages[index]['id'].toString() == id) {
                    CustomToast.show('无法回复自己消息!');
                    return;
                  }
                  Event.emit('add_user_in_controller', barrages[index]);
                }
              },
              behavior: HitTestBehavior.opaque,
            ),
          );
        });
    if (barrages.length <= 4) return view;
    return Expanded(child: view);
  }

  //显示弹幕消息 三种形式
  //我 回复 谁
  //谁 回复 我
  //谁回复 谁
  Widget buildContentWidget(int index) {
    Map map = barrages[index] ?? {};
    //消息内容
    WidgetSpan textSpan = WidgetSpan(
      child: SelectableText(
        "${barrages[index]['words'] ?? ""}",
        style: TextStyle(
          color: Colors.white,
          fontSize: fontSize,
        ),
      ),
    );
    TextStyle style = TextStyle(
      fontSize: fontSize,
      fontWeight: FontWeight.w500,
    );
    //竞标商等级
    WidgetSpan buildBidderLevel(Map data) {
      return WidgetSpan(
        child: data['is_bidder']
            ? Container(
                child: Image.asset(
                  'images/lt_user/level/level_${data['user_level']}.png',
                  width: 22.w,
                  height: 12.w,
                  fit: BoxFit.cover,
                ),
                margin: EdgeInsets.only(right: 10.w),
              )
            : Container(width: 0.w, height: 0.w),
        alignment: PlaceholderAlignment.middle, //居中对齐
      );
    }

    TextSpan getStringWidget(String nickname) {
      return TextSpan(
        text: "${nickname}",
        style: TextStyle(
          color: Color(
            0xFFB2CF87,
          ),
        ),
      );
    }

    //是否有回复显示 当前这条消息
    bool hasBeUser = (map['be_user_info'] ?? {}).isNotEmpty;
    if (hasBeUser) {
      //被回复人的id
      String be_id = map['be_user_info']['id'].toString();
      //回复人id
      String user_id = map['id'].toString();
      //如果被回复的人是我
      if (be_id == id) {
        return Text.rich(
          TextSpan(
            style: style,
            children: [
              buildBidderLevel(map),
              getStringWidget(map['user_nickname'] + " 回复我："),
              textSpan,
            ],
          ),
        );
      } else if (user_id == id) {
        return Text.rich(
          TextSpan(
            style: style,
            children: [
              getStringWidget("我回复 "),
              buildBidderLevel(map['be_user_info']),
              getStringWidget(map['be_user_info']['user_nickname'] + "："),
              textSpan,
            ],
          ),
        );
      } else {
        return Text.rich(
          TextSpan(
            style: style,
            children: [
              buildBidderLevel(map),
              getStringWidget(map['user_nickname']),
              getStringWidget(" 回复 "),
              buildBidderLevel(map['be_user_info']),
              getStringWidget(map['be_user_info']['user_nickname'] + "："),
              textSpan,
            ],
          ),
        );
      }
    }
    return Text.rich(
      TextSpan(
        style: style,
        children: [
          buildBidderLevel(map),
          getStringWidget(map['user_nickname'] + "："),
          textSpan,
        ],
      ),
    );
  }

  //举报
  report(Map<String, dynamic>? map) async {
    HttpUtil.commonRequest(Get.context!, "/api/v1/studio_reports",
            method: HttpUtil.MethodPost,
            queryParameters: map,
            isErrorToast: false,
            isLoading: false)
        .then((value) {
      if (value.statusCode == 200) {
        CustomToast.show("${value.data['msg'] ?? "平台已收到举报"}");
      }
    }).catchError((e) {
      showGetDialog(ReportWordDialog(
        delete: () async {},
        isReport: true,
        deleteWord: map!['words'],
      ));
    });
  }
}
